const jwt = require("jsonwebtoken");
const loginService = require("../service/login.service");
const md5Password = require("../utils/md5-password");
const { PUBLIC_KEY } = require("../config/screct");
const {
  NAME_OR_PASSWORD_IS_incorrect,
  NAME_OR_PASSWORD_IS_REQUIRED,
  TOKEN_EXPIRED_AND_LOGIN_AGAIN,
} = require("../config/error");

// 校验登录
const verifyLogin = async (ctx, next) => {
  // 1、获取前端传来的信息，检测用户是否为空
  const { name, password } = ctx.request.body;
  if (!name || !password) {
    return ctx.app.emit("error", NAME_OR_PASSWORD_IS_REQUIRED, ctx);
  }

  // 2、查询数据库信息，查看账户与密码是否正确
  const findResult = await loginService.find(name);
  const encipherPassword = md5Password(password);
  if (!findResult.length || findResult[0].password !== encipherPassword) {
    ctx.app.emit("error", NAME_OR_PASSWORD_IS_incorrect, ctx);
    return;
  }

  ctx.user = findResult[0];
  await next();
};

// 校验令牌
const verifyAuth = async (ctx, next) => {
  // 获取token
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    return ctx.app.emit("error", TOKEN_EXPIRED_AND_LOGIN_AGAIN, ctx);
  }
  const token = authorization.replace("Bearer ", "");

  try {
    // 用公钥验证token是否正确
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"],
    });

    ctx.user = result;

    await next();
  } catch (error) {
    console.log(error);
    // 解密失败怎么返回错误提示
    return ctx.app.emit("error", TOKEN_EXPIRED_AND_LOGIN_AGAIN, ctx);
  }
};

module.exports = { verifyLogin, verifyAuth };
